const {ccclass, property} = cc._decorator;

/**
 * 所有item要挂载这个组件
 */
@ccclass
export default class ListScrollItem extends cc.Component {
    @property({
        type: [cc.Component.EventHandler],
        tooltip: '用于初始化item数据',
    })
    initItemDataFunc: cc.Component.EventHandler[] = [];
    @property({
        tooltip: '是否固定尺寸',
    })
    isFixed: boolean = true;
    @property({
        type: [cc.Component.EventHandler],
        tooltip: '用于不定尺寸item在初始化时更新item尺寸',
        visible: function () {
            if (this.isFixed) {
                this.getItemSizeFunc = [];
            }
            return !this.isFixed;
        },
    })
    getItemSizeFunc: cc.Component.EventHandler[] = [];
    @property({
        visible: function () {
            this.originItemHeight = this.node.height;
            return !this.isFixed;
        },
    })
    originItemHeight: number = 0;

    private _dataIndex: number = -1; // item数据索引
    private _itemType: string = ''; // item类型，在对象池中区别item
    private _isReSizeBeforeShow: boolean = false;   // 是否需要在显示前获得尺寸

    /**
     * @description 更新item数据
     * @param data item数据
     */
    updateItemData(data: any) {
        if (this.initItemDataFunc.length == 0) {
            cc.warn('没有设置item初始化数据');
            return;
        }

        this.initItemDataFunc.forEach(event => event.emit([data]));
        if (!this.isFixed && this.isResizeBeforeShow) {
            this.isResizeBeforeShow = false;
            this.getItemSizeFunc.forEach(event => event.emit([this.originItemHeight]));
        }
    }

    set dataIndex(index: number) {
        this._dataIndex = index;
    }

    get dataIndex(): number {
        return this._dataIndex;
    }

    set itemType(type: string) {
        this._itemType = type;
    }

    get itemType(): string {
        return this._itemType;
    }

    set isResizeBeforeShow(flag: boolean) {
        this._isReSizeBeforeShow = flag;
    }

    get isResizeBeforeShow(): boolean {
        return this._isReSizeBeforeShow;
    }

    unuse() {
    }

    reuse() {
        this.dataIndex = -1;
        this.itemType = '';
    }
}
